package com.rongzhe.house.login.service;

import com.rongzhe.house.common.cache.CommonCacheUtil;
import com.rongzhe.house.common.constants.Constants;
import com.rongzhe.house.common.resp.ApiResult;
import com.rongzhe.house.common.utils.PasswordUtil;
import com.rongzhe.house.common.utils.RandomNumberCode;
import com.rongzhe.house.login.dao.UserBaseMapper;
import com.rongzhe.house.login.entity.User;
import com.rongzhe.house.sms.AliyunSMSService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author Chengjia
 * @date 2018/3/10 18:15
 */
@Service
public class LoginServiceImpl implements  LoginService{

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private CommonCacheUtil commonCacheUtil;

    @Autowired
    private AliyunSMSService verCodeService;



    @Override
    public ApiResult login(User user) {
        ApiResult result=new ApiResult();
        result.setCode(200);
        result.setMessage("登录成功");
        if(StringUtils.isBlank(user.getMobile())){
            result.setCode(-1);
            result.setMessage("账号为空");

            return result;
        }
        if(StringUtils.isBlank(user.getPassword())){
            result.setCode(-2);
            result.setMessage("密码为空");
            return result;
        }

        if(userBaseMapper.validatePhone(user.getMobile())==0){
            result.setCode(-4);
            result.setMessage("该账号未注册！");
            return  result;
        }
        String salt = userBaseMapper.queryUserSalt(user);
        user.setPassword(PasswordUtil.encrypt(user.getPassword(),salt));
        User login=userBaseMapper.validateUser(user);
        if(null==login){
            result.setCode(-3);
            result.setMessage("账号或者密码错误！");
            return  result;
        }
        User u = new User();
        u.setId(login.getId());
        u.setMobile(login.getMobile());
        u.setIsRember(user.getIsRember());
        u.setNickName(login.getNickName()==null?"荣者游客":login.getNickName().equals("")?"荣者游客":login.getNickName());
        result.setData(u);
        /*String cacheUser=commonCacheUtil.getCacheValue(Constants.USER_LOGIN_KEY+user.getMobile());
        if(user.getIsRember()==1){//缓存信息
            if(StringUtils.isBlank(cacheUser)){
                commonCacheUtil.cacheNxExpire(Constants.USER_LOGIN_KEY+user.getMobile(),JSON.toJSONString(login),60*60*7);
            }
        }*/
        return result;
    }

    @Override
    public ApiResult validatePhone(User user) {
        ApiResult result=new ApiResult();
        result.setCode(200);
        if(StringUtils.isBlank(user.getMobile())){
            result.setCode(-1);
            result.setMessage("手机为空");
            return result;
        }
        if(userBaseMapper.validatePhone(user.getMobile())!=0){
            result.setCode(-2);
            result.setMessage("该手机号已注册");
            return result;
        }
        return result;
    }

    @Override
    public ApiResult validateCode(String mobile, String imgId, String imgVValue, HttpServletRequest request) {
        ApiResult result=new ApiResult();
        result.setCode(200);
        result.setMessage("success");

        if(StringUtils.isBlank(mobile)){
            result.setCode(-1);
            result.setMessage("手机号信息不对");
            return result;
        }
        if(StringUtils.isBlank(imgId)|| StringUtils.isBlank(imgVValue)){
            result.setCode(-2);
            result.setMessage("验证码信息不对");
            return result;
        }
        String sessionCode=(String)request.getSession().getAttribute("code");
        if (!StringUtils.equalsIgnoreCase(imgVValue, sessionCode)) {  //忽略验证码大小写
            result.setCode(-3);
            result.setMessage("图片验证码输入不正确");
            return result;
        }
        //下发验证码

        String cu=commonCacheUtil.getCacheValue(Constants.USER_REGISTER_OCDE_COUNT_KEY);
        if(StringUtils.isBlank(cu)){
            String smsCode= RandomNumberCode.verCode();
            boolean sendCode=verCodeService.sendSms(mobile,Constants.ALSMS_VERCODE_TPLID, smsCode);
            if(!sendCode){
                result.setCode(-4);
                result.setMessage("短信验证码发送失败，稍后重试");
                return result;
            }else{
                commonCacheUtil.cacheNxExpire(Constants.USER_REGISTER_OCDE_KEY+mobile,smsCode,60*5);
                commonCacheUtil.cacheNxExpire(Constants.USER_REGISTER_OCDE_COUNT_KEY,"true",60);
            }
        }else{
            result.setCode(-5);
            result.setMessage("短信验证码已发送,稍后重试");
            return result;
        }

        return result;
    }

    @Override
    public ApiResult doRegister(User user, String vcode) {
        ApiResult result=new ApiResult();
        result.setCode(200);
        result.setMessage("success");

        if(StringUtils.isBlank(user.getMobile())|| StringUtils.isBlank(user.getPassword())){
            result.setCode(-1);
            result.setMessage("注册信息有误");
            return result;
        }
        //获取缓存的下发验证码
        if(StringUtils.isBlank(vcode)){
            result.setCode(-2);
            result.setMessage("短信验证码不为空");
            return result;
        }
        //String  cacheCode="111111";
        String cacheCode=commonCacheUtil.getCacheValue(Constants.USER_REGISTER_OCDE_KEY+user.getMobile());
        if(!vcode.equals(cacheCode)){
            result.setCode(-3);
            result.setMessage("与下发短信不匹配");
            return result;
        }

        String salt = PasswordUtil.randomSalt();
        if(userBaseMapper.validatePhone(user.getMobile())==0){
            user.setStatus(1);
            user.setInsertTime(new Date());
            user.setPassword(PasswordUtil.encrypt(user.getPassword(), salt));
            user.setSalt(salt);
            userBaseMapper.registerUser(user);
        }else{
            result.setCode(-4);
            result.setMessage("已注册");
            return result;
        }
        return result;
    }

    @Override
    public ApiResult validateFindPhoneCode(User user,String vcode) {
        ApiResult result = new ApiResult();
        result.setCode(200);
        result.setMessage("success");
        if(StringUtils.isBlank(user.getMobile())){
            result.setCode(-1);
            result.setMessage("手机信息有误");
            return result;
        }
        if(StringUtils.isBlank(vcode)){
            result.setCode(-2);
            result.setMessage("短信验证码不为空");
            return result;
        }
        //String cacheCode="111111";
        String cacheCode=commonCacheUtil.getCacheValue(Constants.USER_REGISTER_OCDE_KEY+user.getMobile());

        if(!vcode.equals(cacheCode)){
            result.setCode(-3);
            result.setMessage("与下发短信不匹配");
            return result;
        }

        //记录用户找回密码信息
        User byPhone = userBaseMapper.queryByPhone(user);
        if(null!=byPhone){
            result.setData(byPhone.getId());
        }
        return result;
    }

    @Override
    public ApiResult updatePwd(User user) {
        ApiResult result = new ApiResult();
        result.setCode(-1);
        result.setMessage("操作失败");
        if(null!=user&&!StringUtils.isBlank(user.getMobile())&&user.getId()!=0){
            String salt = PasswordUtil.randomSalt();
            user.setUpdateTime(new Date());
            user.setPassword(PasswordUtil.encrypt(user.getPassword(), salt));
            user.setSalt(salt);
            if(userBaseMapper.updateUserPwd(user)>0){
                result.setCode(200);
                result.setMessage("操作成功");
            }
        }
        return result;
    }
}
